<?php

namespace Icsoc\GroupBundle\Controller;

use Doctrine\ORM\NoResultException;
use Icsoc\CoreBundle\Controller\BaseController;
use Icsoc\SecurityBundle\Entity\WinGroup;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * 业务组
 * Class GroupController
 * @package Icsoc\GroupBundle\Controller
 */
class GroupController extends BaseController
{
    /**
     * @return Response
     */
    public function indexAction()
    {
        return $this->render('IcsocGroupBundle:Group:index.html.twig');
    }

    /**
     * 列表；
     * @param Request $request
     * @return Response
     */
    public function listAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('fliter', '');
        /** @var  $em \Doctrine\ORM\EntityManager */
        $em = $this->getDoctrine()->getManager();
        $where = ' AND intro.vccId = :vcc_id AND intro.isDel = 0 ';
        $parameter['vcc_id']  = $this->getUser()->getVccId();
        if (!empty($fliter)) {
            $json = json_decode($fliter, true);
            if (isset($json['keyword']) && !empty($json['keyword'])) {
                $where.="AND intro.groupName like '%".$json['keyword']."%'";
            }
        }

        $query = $em->createQuery(
            "SELECT count(intro) ".
            "FROM IcsocSecurityBundle:WinGroup intro ".
            "WHERE 1=1 ".$where
        )->setParameters($parameter);
        try {
            $single = $query->getSingleResult();
            $count = $single['1'];
        } catch (NoResultException $e) {
            $count = 0;
        }
        if ($count > 0) {
            $totalPage = ceil($count/$rows);
        } else {
            $totalPage = 1;
        }
        if ($page > $totalPage) {
            $page = $totalPage;
        }
        $start = ($page -1 )*$rows;
        /** @var  $query \Doctrine\ORM\Query */
        $query = $em->createQuery(
            'SELECT intro '.
            'FROM IcsocSecurityBundle:WinGroup intro '.
            'WHERE 1=1 '.$where.
            'ORDER BY intro.'.$sidx.' '.$sord
        )->setParameters($parameter);

        $query->setFirstResult($start);
        $query->setMaxResults($rows);
        $all = $query->getResult();
        $reponse['rows'] = $all;
        $reponse['page'] = $page;
        $reponse['total'] = $totalPage;
        $reponse['records'] = $count;
        $serializer = $this->get('serializer');
        $response = $serializer->serialize($reponse, 'json');
        return new Response($response);
    }

    /**
     * 删除业务组
     * @param Request $request
     * @return JsonResponse
     */
    public function delAction(Request $request)
    {
        $ids = $request->get('id', 0);
        $arr = explode(",", $ids);
        $em = $this->getDoctrine()->getManager();
        foreach ($arr as $val) {
            $group = $em->getRepository('IcsocSecurityBundle:WinGroup')->find($val);
            $em->remove($group);
        }
        $logStr = $this->get('translator')->trans('Delete group %str%', array('%str%'=>$ids));
        $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_DELETE, $logStr);
        $em->flush();
        return new JsonResponse(array('message'=>$this->get('translator')->trans('Delete success'),'error'=>0));
    }

    /**
     * 添加业务组
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function addAction(Request $request)
    {
        $group = new WinGroup();
        $form = $this->createForm('group_info_form', $group);
        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            $group->setVccId($this->getUser()->getVccId());
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($group);
                $em->flush();
                $logStr = $this->get('translator')->trans('Add group %str%', array('%str%'=>$group->getGroupName()));
                $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, $logStr);
                $data = array(
                    'data'=>array(
                        'msg_detail'=> $this->get('translator')->trans('Add business group success'),
                        'type'=>'success',
                        'link' => array(
                            array('text'=>$this->get('translator')->trans('Continue to add'),
                                'href'=>$this->generateUrl('icsoc_group_add')),
                            array('text'=>$this->get('translator')->trans('Business group list'),
                                'href'=>$this->generateUrl('icsoc_group_index')),
                        )
                    )
                );
                return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
            }
        }
        return $this->render("IcsocGroupBundle:Group:groupInfo.html.twig", array(
            'form' => $form->createView()
        ));
    }


    /**
     * 编辑业务组
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function editAction(Request $request)
    {
        $id = $request->get('id', '');
        $em = $this->getDoctrine()->getManager();
        /** @var  $group \Icsoc\SecurityBundle\Entity\WinGroup*/
        $group = $em->getRepository('IcsocSecurityBundle:WinGroup')->find($id);
        $oldName = $group->getGroupName();
        $form = $this->createForm('group_info_form', $group);
        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->flush();
                if ($oldName != $group->getGroupName()) {
                    $content = $oldName.'=>'.$group->getGroupName();
                    $logStr = $this->get('translator')->trans('Update group %str%', array('%str%'=>$content));
                    $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_UPDATE, $logStr);
                }
                $data = array(
                    'data'=>array(
                        'msg_detail'=> $this->trans('Edit business group success'),
                        'type'=>'success',
                        'link' => array(
                            array('text'=>$this->trans('return'),
                                'href'=>'javascript:history.go(-1);'),
                            array('text'=>$this->trans('Business group list'),
                                'href'=>$this->generateUrl('icsoc_group_index')),
                        )
                    )
                );
                return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
            }
        }
        return $this->render("IcsocGroupBundle:Group:groupInfo.html.twig", array(
                'form' => $form->createView(),
                'group_id'=>$id
            ));
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function checkGroupAction(Request $request)
    {
        $vccId = $this->getVccId();
        $groupName = $request->get('groupName');
        $id = $request->get('group_id', '');
        $em = $this->getDoctrine()->getManager();
        $res = $em->getRepository("IcsocSecurityBundle:WinGroup")->existGroupName($vccId, $groupName, $id);
        if ($res) {
            return new Response("false");
        }
        return new Response("true");
    }
}
